package kr.co.hk.fac;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import kr.co.hk.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class FacDetails extends Activity {

	private ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;

	private String phoneNum="";
	private String homepage="";
	private String email="";
	private String addr="";
	private String facName="";
	private String bus="";
	private String pur="";
	
	private String url="";
	

	private Menu mMenu;
	private TextView textView2;
	private TextView textView4;
	private TextView textView6;
	private TextView textView8;
	private TextView textView10;
	private TextView textView12;
	private TextView textView14;
	private boolean pageEx = false;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		mMenu = menu;
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.fac_det_menu, mMenu);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.homepage:
			homePage();

			break;
		case R.id.locationInfo:
			locationInfo();

			break;
		case R.id.emailSend:
			emailSend();

			break;
		case R.id.telCall:
			tealCall();

			break;

		default:
			break;
		}

		return true;

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.fac_details);

		textView2 = (TextView) findViewById(R.id.text02);
		textView4 = (TextView) findViewById(R.id.text04);
		textView6 = (TextView) findViewById(R.id.text06);
		textView8 = (TextView) findViewById(R.id.text08);
		textView10 = (TextView) findViewById(R.id.text10);
		textView12 = (TextView) findViewById(R.id.text12);
		textView14 = (TextView) findViewById(R.id.text14);
		Bundle extra = getIntent().getExtras();

		if (extra != null) {
			
			String seq = extra.getString("seq");
			url="http://www.women.go.kr/new_women/women/info/fac/selectFacDetl.do?seq="
					+ seq;
			threadStart();
		}

			
		

		textView4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				locationInfo();

			}

		});
		textView6.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tealCall();
			}
		});

		textView8.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				emailSend();

			}
		});

		textView14.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				homePage();
			}
		});

	}

	private void homePage() {
		if (homepage.equals("") || homepage.equals(null)
				|| homepage.equals("http://")) {
			toast("잘못된 페이지 입니다.");

		} else {
			Uri uri;
			if (homepage.contains("http")) {
				uri = Uri.parse(homepage);
			} else {
				uri = Uri.parse("http://" + homepage);
			}
			startActivity(new Intent(Intent.ACTION_VIEW, uri));
		}
	}

	private void emailSend() {
		if (email.equals(null) || email.equals("")) {
			toast("e-mail 주소를 찾을수 없습니다.");
		} else {
			Intent emailIntent = new Intent(Intent.ACTION_SEND);
			emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
			emailIntent.setType("plain/text");

			try {
				startActivity(Intent.createChooser(emailIntent, "메일 설정을 해주세요!"));
			} catch (android.content.ActivityNotFoundException ex) {
				toast("There are no email clients installed.");
			}

		}

	}

	private void locationInfo() {
		if (!addr.equals(null)) {
			Intent locationIntent = new Intent(this, FacLocationMapView.class);
			locationIntent.putExtra("addr", addr);
			locationIntent.putExtra("facName", facName);
			locationIntent.putExtra("enAddr", encoder(addr));
			startActivity(locationIntent);
		} else {
			toast("주소를 찾을수 없습니다.");
		}
	}

	private void tealCall() {

		if (phoneNum.equals("") || phoneNum.equals(null)) {
			toast("전화번호가 없습니다.");
		} else {
			call_dialog();
		}
	}

	private void getFacDetail(String urlStr) {
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									"utf-8"));
					StringBuffer msg = new StringBuffer(); 
					String line = "";
					
					while ((line = br.readLine()) != null) {
						msg.append(line);
					}
						String organSou = msg.substring(msg.indexOf("시설명</th>"), msg
								.indexOf("분류명</th>"));
						String organDes = organSou.substring(organSou.indexOf("<td>") + 4,
								organSou.indexOf("</td>"));
						// 주소 찾기
						String addrSou = msg.substring(msg.indexOf("<th>주소</th>"), msg
								.indexOf("운영주체</th>"));
						String addrDes = addrSou.substring(
								addrSou.indexOf("<td colspan") + 16, addrSou
										.indexOf("&nbsp;<a href="));

						// 대표tel 찾기
						String telSou = msg.substring(msg.indexOf("대표 Tel</th>"), msg
								.indexOf("FAX</th>"));
						String telDes = telSou.substring(telSou.indexOf("<td>") + 4, telSou
								.indexOf("</td>"));

						// 대표 이메일 찾기
						String emailSou = msg.substring(msg.indexOf("대표이메일 </th>"), msg
								.indexOf("기관소개</th>"));
						String emailDes = emailSou.substring(emailSou
								.indexOf("<td colspan") + 16, emailSou.indexOf("</td>"));

						// 홈페이지 찾기
						String pageSou = msg.substring(msg.indexOf("홈페이지주소</th>"), msg
								.indexOf("담당자 Tel</th>"));
						String pageDes = pageSou.substring(
								pageSou.indexOf("<td colspan") + 16, pageSou
										.indexOf("</td>"));

						String purSou = msg.substring(msg.indexOf("설립목적</th>"), msg
								.indexOf("주요사업</th>"));
						String purDes = purSou
								.substring(purSou.indexOf("<td colspan") + 16, purSou
										.indexOf("</td>"));
						// 주요사업
						String busSou = msg.substring(msg.indexOf("주요사업</th>"), msg
								.indexOf("등록관청</th>"));
						String busDes = busSou
								.substring(busSou.indexOf("<td colspan") + 16, busSou
										.indexOf("</td>"));

						
						
						
						phoneNum = telDes;
						homepage = pageDes;
						email = emailDes;
						addr = addrDes;
						facName =organDes;
						bus = busDes;
						pur = purDes;
						
						
					br.close();
				}
				conn.disconnect();
			}
		} catch (Exception ex) {
			pageEx = true;
			ex.printStackTrace();
		}
	}

	private void call_dialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("통화하시겠습니까?").setCancelable(false).setPositiveButton(
				"Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						startActivity(new Intent(Intent.ACTION_CALL, Uri
								.parse("tel:" + phoneNum)));
					}
				}).setNegativeButton("No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();

	}


	private String encoder(String str) {
		String encodedStr = "";
		try {
			encodedStr = URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodedStr;
	}

	
	private void threadStart() {
		pageEx = false;
		showDialog(PROGRESS_DIALOG);
		new Thread() {
			public void run() {
				getFacDetail(url);
				Message msg = handler.obtainMessage();
				handler.sendMessage(msg);
			}
		}.start();
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			FacDetails.this.removeDialog(PROGRESS_DIALOG);
			if (pageEx) {
				excePro();
			} else {
				textView2.setText(facName);
				textView10.setText(pur);
				textView12.setText(bus);
				textView4.setText(Html.fromHtml("<u>" + addr + "</u>"));
				textView6.setText(Html.fromHtml("<u>" + phoneNum + "</u>"));
				textView8.setText(Html.fromHtml("<u>" + email + "</u>"));
				textView14.setText(Html.fromHtml("<u>" + homepage + "</u>"));
			}

		}
	};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:

			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Now loading..");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(false);
			return progressDialog;

		}
		return null;

	}

	private void excePro() {
		toast("페이지 로딩시 오류가  있습니다. \n 네트워크 확인 후 다시 시도 하세요!");
		onBackPressed();
	}
	private void toast(String string) {
		Toast.makeText(FacDetails.this, string, Toast.LENGTH_SHORT).show();
	}

}
